package com.lzf.yh.userService.impl;

import com.lzf.yh.commons.JsonBean;
import com.lzf.yh.commons.MD5Util;
import com.lzf.yh.dao.UserMapper;
import com.lzf.yh.entity.User;
import com.lzf.yh.userService.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public JsonBean insertUser(User user) {
        JsonBean jsonBean = new JsonBean(-1, "注册失败", null);
        User byPhone = userMapper.selectByPhone(user.getPhone());
        User dbUser = userMapper.selectByUserName(user.getUserName());

        if (dbUser != null) {
            jsonBean = new JsonBean(-1, "用户名重复", null);
        } else {
            if (byPhone != null) {
                jsonBean = new JsonBean(-1, "手机号重复", null);
            } else {
                String salt = MD5Util.getSalt();
                String encrypt = MD5Util.encrypt(user.getPwd() + salt);
                user.setSalt(salt);
                user.setPwd(encrypt);
                user.setIsdelete("1");
                int i = userMapper.insert(user);
                if (i > 0) {
                    jsonBean = new JsonBean(0, "注册成功", null);
                }
            }
        }
        return jsonBean;
    }

    @Override
    public JsonBean selectUser(User user, HttpSession session) {
        JsonBean jsonBean = new JsonBean(-1, "账号或密码错误", null);
        User dbUser = userMapper.selectByUserName(user.getUserName());
        if (dbUser != null) {
            if (dbUser.getIsdelete().equals("0")) {
                jsonBean = new JsonBean(-1, "此账户已被冻结", null);
            } else {
                String salt = dbUser.getSalt();
                String encrypt = MD5Util.encrypt(user.getPwd() + salt);
                if (encrypt.equals(dbUser.getPwd())) {
                    session.setAttribute("userInfo", dbUser);
                    jsonBean = new JsonBean(0, "登录成功", null);
                }
            }
        }
        return jsonBean;
    }

}
